package pri.hillchen.std.netty.echo;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.Scanner;

/**
 * Created by hillchen on 2018/3/31.
 */
public class EchoClientHandler extends ChannelHandlerAdapter {
    public  static final String ORDER_EXIT = "-end";
    public  static final String ORDER_CONNECT = "START-CONNECT";

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        ctx.writeAndFlush(Unpooled.copiedBuffer((ORDER_CONNECT + EchoServer.ORDER_END).getBytes()));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //如果返回时的是退出命令，则执行退出操作
        if(ORDER_EXIT.equals(msg)){
            System.out.println("server req:断开连接！" );
            ctx.close();
        }else{
            System.out.println("server req:" + msg);
            Scanner scanner = new Scanner(System.in);
            String content= scanner.next();
            ctx.writeAndFlush(Unpooled.copiedBuffer((content + EchoServer.ORDER_END).getBytes()));
        }
    }
}
